package cn.edu.zjicm.wordsnet_d.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.AddSchoolActivity;
import cn.edu.zjicm.wordsnet_d.activity.AddSchoolActivity.SelectType;
import cn.edu.zjicm.wordsnet_d.adapter.AddSchoolAdapter;
import cn.edu.zjicm.wordsnet_d.data.Location;
import cn.edu.zjicm.wordsnet_d.data.School;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.db.LocationAndSchoolFactory;
import cn.edu.zjicm.wordsnet_d.synchronize.SchoolInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;

public class AddSchoolFragment extends Fragment implements OnItemClickListener {

	private View mView;
	private LinearLayout searchLayout;
	private EditText searchEdit;
	private ImageView searchClear;
	private ListView resultList;
	private ViewFlipper resultFlipper;

	private AddSchoolActivity mContext;
	public SelectType type;
	public int id;
	private int schoolLevel;
	private List<Location> list;
	private List<School> schoolList;
	private School school;
	private AddSchoolAdapter adapter = null;

	public AddSchoolFragment(AddSchoolActivity mContext, SelectType type, int id, int schoolLevel) {
		this.mContext = mContext;
		this.type = type;
		this.id = id;
		this.schoolLevel = schoolLevel;
	}

	public AddSchoolFragment() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_add_school, null);
		findView();
		initView();
		return mView;
	}

	private void initView() {
		List<String> dataList;
		switch (type) {
		case EDU:
			dataList = new ArrayList<String>();
			dataList.add("大学");
			dataList.add("高中");
			dataList.add("中专技校");
			dataList.add("初中");
			adapter = new AddSchoolAdapter(mContext, dataList, false);
			break;

		case PRO:
			list = LocationAndSchoolFactory.getInstance(mContext).getProvincesList();
			dataList = new ArrayList<String>();
			for (Location location : list) {
				dataList.add(location.getName());
			}
			adapter = new AddSchoolAdapter(mContext, dataList, false);
			break;

		case CITY:
			dataList = new ArrayList<String>();
			list = LocationAndSchoolFactory.getInstance(mContext).getCitysList(id);
			for (Location location : list) {
				dataList.add(location.getName());
			}
			adapter = new AddSchoolAdapter(mContext, dataList, false);
			break;

		case DIS:
			if (id <= 4) {
				list = LocationAndSchoolFactory.getInstance(mContext).getRegionsListOfMunicipality(id);
			} else
				list = LocationAndSchoolFactory.getInstance(mContext).getRegionsList(id);
			dataList = new ArrayList<String>();
			for (Location location : list) {
				dataList.add(location.getName());
			}
			adapter = new AddSchoolAdapter(mContext, dataList, false);
			break;

		case SCHOOL:
			// adapter = toGetSchoolListFromDB();
			toGetSchoolList(schoolLevel, id);
			break;
		}
		resultList.setAdapter(adapter);
		resultList.setOnItemClickListener(this);
		searchEdit.addTextChangedListener(textWatcher);
		searchClear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				searchEdit.setText("");
				searchClear.setVisibility(View.GONE);
				resultFlipper.setDisplayedChild(0);
			}
		});
	}

	private void findView() {
		searchLayout = (LinearLayout) mView.findViewById(R.id.search_layout);
		searchEdit = (EditText) mView.findViewById(R.id.search_edit);
		searchClear = (ImageView) mView.findViewById(R.id.search_edit_clear);
		resultList = (ListView) mView.findViewById(R.id.result_list);
		resultFlipper = (ViewFlipper) mView.findViewById(R.id.resultFlipper);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		switch (type) {
		case EDU:
			mContext.schoolLevel = position + 1;
			mContext.type = SelectType.PRO;
			mContext.updateView();
			break;

		case PRO:
			mContext.selectedID = list.get(position).getId();
			if (schoolLevel == 1) {
				mContext.type = SelectType.SCHOOL;
			} else {
				if (id < 4) {
					mContext.type = SelectType.DIS;
				} else {
					mContext.type = SelectType.CITY;
				}
			}
			mContext.updateView();
			break;

		case CITY:
			mContext.selectedID = list.get(position).getId();
			List<Location> locationList = LocationAndSchoolFactory.getInstance(mContext).getRegionsList(mContext.selectedID);
			if (locationList.size() == 1 && locationList.get(0).getName().equals("null"))
				mContext.type = SelectType.SCHOOL;
			else
				mContext.type = SelectType.DIS;
			mContext.updateView();
			break;

		case DIS:
			mContext.selectedID = list.get(position).getId();
			mContext.type = SelectType.SCHOOL;
			mContext.updateView();
			break;

		case SCHOOL:
			school = schoolList.get(position);
			toSetSchoolID(school.getId());
			break;
		}
	}

	TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (searchEdit.getText().length() > 0) {
				searchClear.setVisibility(View.VISIBLE);
			} else {
				searchClear.setVisibility(View.INVISIBLE);
			}
			if (schoolLevel == 1) {
				schoolList = LocationAndSchoolFactory.getInstance(mContext).getUniversity(id, searchEdit.getText().toString());
			} else {
				schoolList = LocationAndSchoolFactory.getInstance(mContext).getHighSchool(id, schoolLevel, searchEdit.getText().toString());
			}
			if (schoolList.size() == 0) {
				resultFlipper.setDisplayedChild(1);
			} else {
				resultFlipper.setDisplayedChild(0);
				ArrayList<String> array = new ArrayList<String>();
				for (School school : schoolList) {
					array.add(school.getSchoolName());
				}
				adapter = new AddSchoolAdapter(mContext, array, false);
				resultList.setAdapter(adapter);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	};

	protected AddSchoolAdapter toGetSchoolListFromDB() {
		ArrayList<String> array = new ArrayList<String>();
		if (schoolLevel == 1) {
			schoolList = LocationAndSchoolFactory.getInstance(mContext).getUniversity(id);
		} else {
			schoolList = LocationAndSchoolFactory.getInstance(mContext).getHighSchool(id, schoolLevel);
		}
		for (School school : schoolList) {
			array.add(school.getSchoolName());
		}
		adapter = new AddSchoolAdapter(mContext, array, false);
		// LogUtil.e("学校列表", "array=" + array.toString());
		searchLayout.setVisibility(View.VISIBLE);
		return adapter;
	}

	void updateSchoolList(List<School> schoolList) {
		if (schoolList == null)
			return;
		this.schoolList = schoolList;
		ArrayList<String> array = new ArrayList<String>();
		for (School school : schoolList) {
			array.add(school.getSchoolName());
		}
		adapter = new AddSchoolAdapter(mContext, array, false);
		resultList.setAdapter(adapter);
		// LogUtil.e("学校列表", "array=" + array.toString());
		searchLayout.setVisibility(View.VISIBLE);
	}

	protected void toGetSchoolList(int schollLevel, int locationId) {
		getSchoolListHandler.sendMessage(getSchoolListHandler.obtainMessage(UserInterface.MSG_START));
		SchoolInterface.getInstance(getActivity()).getSchoolList(schoolLevel, locationId, getSchoolListHandler);
	}

	Handler getSchoolListHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}
			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(getActivity(), null, "正在获取学校数据");
				break;
			case UserInterface.MSG_SUCCESS:
				List<School> schollList = (List<School>) msg.obj;
				LocationAndSchoolFactory.getInstance(getActivity()).importTableSchoolList(schollList);
				updateSchoolList(schollList);
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(getActivity(), "获取学校数据失败，请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(getActivity(), "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(getActivity(), "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	protected void toSetSchoolID(int sid) {
		setSchoolIDHandler.sendMessage(setSchoolIDHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(getActivity()).setSchoolID(sid, setSchoolIDHandler);
	}

	Handler setSchoolIDHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START) {
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}
				mContext.finish();
			}
			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(getActivity(), null, "正在设置学校信息");
				break;
			case UserInterface.MSG_SUCCESS:
				AppPreference.setSchoolId(mContext, school.getId());
				AppPreference.setSchoolName(mContext, school.getSchoolName());
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(getActivity(), "设置学校信息失败，请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(getActivity(), "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(getActivity(), "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
}
